package leetCode;

import com.sun.deploy.util.StringUtils;

import java.util.*;

/**
 * @PackageName: leetCode
 * @ClassName: LeetCode917
 * @Author: chen jinxu
 * @Date: 2022/2/23 22:29
 * 给你一个字符串 s ，根据下述规则反转字符串：
 *
 * 所有非英文字母保留在原有位置。
 * 所有英文字母（小写或大写）位置反转。
 * 返回反转后的 s 。
 * 输入：s = "ab-cd"
 * 输出："dc-ba"
 * 输入：s = "a-bC-dEf-ghIj"
 * 输出："j-Ih-gfE-dCba"
 * 输入：s = "Test1ng-Leet=code-Q!"
 * 输出："Qedo1ct-eeLg=ntse-T!"
 */
public class LeetCode917 {
    public static void main(String[] args) {
        String s = "728}";
        String result = reverseOnlyLetters(s);
        System.out.println(result);
    }
    public static String reverseOnlyLetters(String s) {
        int n = s.length();
        char[] arr = s.toCharArray();
        int left = 0;
        int right = n - 1;
        while (true) {
            while (left < n && !Character.isLetter(s.charAt(left))) {
                left++;
            }
            while (right >= 0 && !Character.isLetter(s.charAt(right))) {
                right--;
            }
            if (left >= right) {
                break;
            }
            swap(arr, left, right);
            left++;
            right--;
        }
        return String.valueOf(arr);
    }

    private static void swap(char[] arr, int left, int right) {
        char tem = arr[left];
        arr[left] = arr[right];
        arr[right] = tem;
    }

}
